package com.example.aicooking.service.imp;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.aicooking.entity.User;
import com.example.aicooking.entity.UserDetail;
import com.example.aicooking.entity.dto.UserUpdateDTO;
import com.example.aicooking.entity.vo.UserBasicVO;
import com.example.aicooking.entity.vo.UserDetailVO;
import com.example.aicooking.mapper.UserDetailMapper;
import com.example.aicooking.mapper.UserMapper;
import com.example.aicooking.service.UserService;
import com.example.aicooking.util.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserDetailMapper userDetailMapper;

    @Override
    @Transactional
    public boolean register(User user) {
        // 参数校验
        if (user.getUserName() == null || user.getUserName().trim().isEmpty()) {
            throw new RuntimeException("用户名不能为空");
        }
        if (user.getPassword() == null || user.getPassword().trim().isEmpty()) {
            throw new RuntimeException("密码不能为空");
        }

        // 检查用户名是否存在
        List<User> existUsers = baseMapper.searchByUsername(user.getUserName());
        if (!existUsers.isEmpty()) {
            throw new RuntimeException("用户名已存在");
        }

        // 设置用户信息
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        user.setCreateTime(new Date());

        // 保存用户信息
        boolean saveResult = this.save(user);
        if (!saveResult) {
            throw new RuntimeException("用户注册失败");
        }

        // 创建用户健康信息
        UserDetail userDetail = new UserDetail();
        userDetail.setUserId(user.getUserId());
        userDetail.setBmi(20.0f);
        userDetail.setTaste("无特殊偏好");
        userDetail.setAllergen("无");
        userDetail.setDietaryRestrictions("无");

        try {
            userDetailMapper.insertUserDetail(userDetail);
        } catch (Exception e) {
            log.error("创建用户健康信息失败", e);
            throw new RuntimeException("创建用户健康信息失败");
        }

        return true;
    }

    @Override
    public User login(String username, String password) {
        List<User> users = baseMapper.searchByUsername(username);
        if (users.isEmpty()) {
            throw new RuntimeException("用户不存在");
        }
        
        User user = users.get(0);
        if(!user.getPassword().equals(DigestUtils.md5DigestAsHex(password.getBytes()))) {
            throw new RuntimeException("密码错误");
        }
        user.setLastLoginTime( new Date());
        userMapper.updateLastLoginTime(user);
        return user;
    }

    @Override
    public UserBasicVO getBasicInfo(Integer userId) {
        UserBasicVO basicInfo = userMapper.getBasicInfo(userId);
        if (basicInfo == null) {
            throw new BusinessException("用户不存在");
        }
        return basicInfo;
    }

    @Override
    public UserDetailVO getDetailInfo(Long userId) {
        UserDetailVO detailInfo = userMapper.getDetailInfo(userId);
        if (detailInfo == null) {
            throw new BusinessException("用户不存在");
        }
        return detailInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateUserInfo(UserUpdateDTO updateDTO) {
        log.info("开始更新用户信息: {}", updateDTO);
        // 先检查用户是否存在
        if (updateDTO.getUserId() == null) {
            throw new BusinessException("用户ID不能为空");
        }
        // 检查昵称是否已存在
        if (StringUtils.isNotBlank(updateDTO.getNickname())) {
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getNickname, updateDTO.getNickname())
                    .ne(User::getUserId, updateDTO.getUserId());
            if (userMapper.selectCount(wrapper) > 0) {
                throw new BusinessException("昵称已被使用");
            }
        }

        User user = new User();
        user.setUserId(updateDTO.getUserId());  // 明确设置userId
        user.setNickname(updateDTO.getNickname());
        user.setSignature(updateDTO.getSignature());
        user.setGender(updateDTO.getGender());
        user.setAge(updateDTO.getAge());
        user.setPhone(updateDTO.getPhone());

        log.info("更新用户信息: {}", user);

        // 执行更新
        int rows = userMapper.updateById(user);
        log.info("更新结果: {}", rows);

        return userMapper.updateById(user) > 0;
    }

    @Override
    public boolean checkUserIdExists(int userId) {
        // 检查数据库中是否已存在该 ID
        return userMapper.findByUserId(userId) != null;
    }
}